from __future__ import absolute_import

from scopt.mpu import devel
from . import message

_MODULES = ()


def set_modules(modules):
    global _MODULES
    _MODULES = modules


@message(type='devel.mpu_list',
         version='0.1',
         reqd={},
         resd={})
def handle(data_packet):
    data_packet = devel.mpu_list_init(data_packet, 'business')
    for module in _MODULES:
        module_name = module.__name__.replace('scopt.mpu.business.', '')
        node = module_name.replace('.handlers', '')
        data_packet = devel.mpu_list_append(data_packet, node, 'module', node,
                                            'business')
        module_registry = module.message.registry()
        versions = []
        for handler_type, handler in module_registry.items():
            if handler.VERSION not in versions:
                data_packet =\
                    devel.mpu_list_append(data_packet, handler.VERSION + node,
                                          'version',
                                          'Version: ' + handler.VERSION, node)
                versions.append(handler.VERSION)
            data_packet =\
                devel.mpu_list_append(data_packet, handler_type, 'message',
                                      handler.TYPE, handler.VERSION + node)
    return data_packet
